package cn.javass.dp.flyweight.example5;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SecurityMgr {

    private static SecurityMgr securityMgr = new SecurityMgr();

    private SecurityMgr() {
    }

    public static SecurityMgr getInstance() {
        //静态不能用this
        return securityMgr;
    }

    /**
     * 运行期间，用来存放人员对应的权限 ，在web应用中 通常放到session中
     */
    private Map<String, Collection<Flyweight>> map = new HashMap<>();

    /**
     * 模拟登陆功能
     * @param user
     */
    public void login (String user) {
        Collection<Flyweight> col = queryByUser(user);
        map.put(user,col);
    }

    public boolean hasPremit(String user, String securityEntity, String premit) {
        //Collection<Flyweight> col = map.get(user);
        //有缓存的存在  每次先取缓存中的数据，而不是直接在内存中取值

        Collection<Flyweight> col = queryByUser(user);
        if (col == null || col.size() == 0) {
            System.out.println("该用户没有任何权限");
            return false;
        }
        for (Flyweight fm : col) {
            System.out.println("fm == " + fm);
            if (fm.match(securityEntity, premit)) {
                return true;
            }
        }
        return false;
    }

    private Collection<Flyweight> queryByUser(String user) {
        Collection<Flyweight> col = new ArrayList<>();

        for (String s : TestDB.colDB) {
            String ss[] = s.split(",");
            if (ss[0].equals(user)) {
                Flyweight fm =null;
                if (ss[3].equals("2")) {
                    //表示组合数据
                    fm = new UnsharedConcreteFlyweight();
                    String tempSs[] = TestDB.mapDB.get(ss[1]);
                    for (String tempS : tempSs) {
                        Flyweight tempFm = FlyweightFactory.getInstance().getFlyweight(tempS);
                        fm.add(tempFm);
                    }
                } else {
                    fm = FlyweightFactory.getInstance().getFlyweight(ss[1] +"," + ss[2]);
                }

                col.add(fm);
            }
        }

        return col;
    }

}
